package wsi.task.typedetector;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.rygh.core.html.table.HtmlTable;
import org.rygh.core.html.table.TableData;
import org.rygh.core.html.table.TableTuple;
import org.rygh.core.util.UIo;

import wsi.dataguide.tree.WSXmlLeaf;
import wsi.function.DirManager;
import wsi.task.TaskRoutine;

public class TypeDetector extends TaskRoutine {
	@SuppressWarnings("unused")
	private final String serviceName;
	private final List<TypeInfo> typeInfoList = new ArrayList<>();

	private final AbstractDetector[] detectors = {
	/**/new DateDetector(),
	/**/new NumberDetector(),
	/**/new BooleanDetector(),
	/**/new CountryDetector(), };

	private final SetDetector setDetector = new SetDetector();

	public TypeDetector(DirManager dir) {
		super(dir);

		this.serviceName = dir.getServiceName();
	}

	@Override
	public void compute() {
		log.info("detecting type for " + function.getName());

		detect2(dataGuide.getAllLeaves());
	}

	private void detect2(List<WSXmlLeaf> list) {
		TypeInfo info;

		for (WSXmlLeaf i : list) {

			log.info("detecting " + i.getValue().getName());

			info = new TypeInfo(i);

			List<String> values = i.getValue().getValues();
			double conf;
			boolean typed = false;

			for (AbstractDetector j : detectors) {
				conf = j.detect(values);

				if (conf > .5) {
					info.addType(j.getName(), conf);
					typed = true;
				}
			}

			if (!typed) {
				conf = setDetector.detect(values, i.getValue().getValueList());

				if (conf > .5) {
					info.addType(setDetector.getName(), conf);
					info.setSetValue(setDetector.getSetValue());
				}
			}

			typeInfoList.add(info);
		}

	}

	public List<TypeInfo> getTypeInfoList() {
		return typeInfoList;
	}

	@Override
	public String save() {
		UIo.saveFile(new File(dir.getDebugDir(), "_debug_dg_type.txt"),
				toString());

		//

		// UIo.saveFile(
		// new File(dir.getDataGuidesDir(), String.format(
		// "%s_%s_type.txt", serviceName, function.getName()))
		// .getAbsolutePath(), toString());

		return "";
	}

	public HtmlTable toHtmlTable() {
		TableData valueList = new TableData();
		TableTuple tuple = new TableTuple();

		tuple.add("Tag");
		tuple.add("Type");
		tuple.add("Percentage");
		tuple.add("XPath");

		valueList.add(tuple);

		for (TypeInfo i : typeInfoList)
			valueList.add(i.getCells());

		return new HtmlTable(function.getName(), valueList);
	}

	@Override
	public String toString() {
		StringBuilder sbuilder = new StringBuilder();

		for (TypeInfo i : typeInfoList) {
			sbuilder.append(i);
			sbuilder.append("\r\n");
		}

		return sbuilder.toString();
	}
}
